package com.qingcheng.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/item")
public class itemController {

    @Reference
    private SpuService spuService;

    @Reference
    private SkuService skuService;


    @Reference
    private CategoryService categoryService;

    @Autowired
    private TemplateEngine templateEngine;


    @Value("${pagePath}")
    private String pagePath;

    @GetMapping("/text")
    public void text(String spuId){
        //查询商品信息
        Goods goods =spuService.findGoodsById(spuId);
        //获取SPU信息  Goods: Spu  List<Sku>
        Spu spu = goods.getSpu();
        //获取SKU列表
        List<Sku> skuList = goods.getSkuList();
        //创建页面，(每个sku为一个页面)

    }


    @GetMapping("/createPage")
    public void createPage(String spuId){
        //查询商品信息
        Goods goods =spuService.findGoodsById(spuId);
        //获取SPU信息  Goods: Spu  List<Sku>
        Spu spu = goods.getSpu();
        //获取SKU列表
        List<Sku> skuList = goods.getSkuList();

        //查询商品分类
        List<String> categoryList = new ArrayList<String>();
        //一级分类
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());
        //二级分类
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());
        //三级分类
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());


        //构建sku的地址列表
        Map<String,String> urlMap = new HashMap<>();
        for (Sku sku : skuList) {
            if ("1".equals(sku.getStatus())) {
                String specJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()),SerializerFeature.MapSortField);
                urlMap.put(specJson, sku.getId() + ".html");
            }
        }



        //创建页面，(每个sku为一个页面)
        for (Sku sku : skuList) {
            //获取上下文
            Context context = new Context();
            //创建数据模型
            // TODO 放在for循环外面和里面的区别
            Map<String,Object> dataModel = new HashMap<>();
            dataModel.put("spu",spu);
            dataModel.put("sku",sku);
            dataModel.put("categoryList",categoryList);
            //sku图片列表
            dataModel.put("skuImages",sku.getImages().split(","));
            //spu图片列表
            dataModel.put("spuImages",spu.getImages().split(","));
            //spu参数列表
            Map paraItems = JSON.parseObject(spu.getParaItems());
            //sku列表
            dataModel.put("paraItems",paraItems);
            Map<String,String> specItems=(Map)JSON.parseObject(sku.getSpec());
            dataModel.put("specItems",specItems);

            //规格选择面板
            Map<String,List> specMap = (Map) JSON.parse(spu.getSpecItems());
            for (String key : specMap.keySet()) {
                List<String> list = specMap.get(key);
                List<Map> mapList = new ArrayList<Map>();
                for (String value : list) {//循环规格选项值
                    Map map = new HashMap();
                    map.put("option",value);
                    if (specItems.get(key).equals(value)){//如果和当前的规格相同则选中
                        map.put("checked",true);
                    }else {
                        map.put("checked",false);
                    }

                    Map<String,String> spec = (Map)JSON.parseObject(sku.getSpec());//当前的spec
                    spec.put(key,value);
                    String specJson = JSON.toJSONString(spec, SerializerFeature.MapSortField);

                    map.put("url",urlMap.get(specJson));
                    mapList.add(map);
                }
                specMap.put(key,mapList);//用新集合覆盖原集合
            }
            dataModel.put("specMap",specMap);//规格面板

            context.setVariables(dataModel);

            //准备文件
            File dir = new File(pagePath);
            //创建文件
            if (!dir.exists()){
                dir.mkdirs();
            }
            File dest = new File(dir,sku.getId()+".html");

            //生成页面
            try {
                PrintWriter writer = new PrintWriter(dest,"UTF-8");
                templateEngine.process("item",context,writer);
                System.out.println("生成静态页面");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
